import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTokenTime } from '@/utils/auth'
import router from '@/router'
// import { Loading } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// request interceptor
service.interceptors.request.use((config) => {
  /*  Loading.service({
              target: document.querySelector('.app-main'),
              background: 'rgba(255, 255, 255,.0)'
            })*/
  // 携带Token
  if (store.getters.token) {
    // 判断token是否过期
    const flag = determineWhetherTheTokenHasExpired()
    if (flag) {
      store.commit('user/logout') // 退出登录清除Token
      router.push('/login')
      return Promise.reject(new Error('登录过期,请重新登录')) // 抛出异常给相应拦截器
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config
}
)

// response interceptor
service.interceptors.response.use(
  ({ data }) => {
    // 成功
    const { data: res, message, success } = data
    // 判断后端返回的数据,
    if (success) return res // 真正的成功
    Message.error(message)
    return Promise.reject(new Error(message))
  }, (e) => {
    // 失败
    const ErrorStatus = e.response && e.response.status // 状态码
    switch (ErrorStatus) {
      case 401 :
        store.commit('user/logout') // 退出登录清除Token
        router.push('/login')
        Message.error('登录过期请重新登录')
        break
      default:
        Message.error(e.message)
    }

    return Promise.reject(e)
  }
)

// 判断token是否过期
function determineWhetherTheTokenHasExpired() {
  const timeout = 2 * 3600 * 1000 // 约定的超时时间
  const currentTime = Date.now() // 当前事件戳
  const tokenTime = getTokenTime() // token时间戳
  return (currentTime - tokenTime) >= timeout
}

export default service
